package com.project.study.farming.common.log;

import cn.hutool.json.JSONArray;
import com.project.study.farming.common.anno.ActionLog;
import com.project.study.farming.common.entity.po.LogPo;
import com.project.study.farming.common.utils.BeanMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * aop记录日志
 * @since 2020-03-10
 */
@Aspect
@Component
public class SaveLog {

    @Autowired
    private BeanMapper beanMapper;

    @Pointcut("@annotation(com.project.study.farming.common.anno.ActionLog)")
    public void pointCut(){
    }

    @Around("pointCut()")
    public Object afterRetuen(ProceedingJoinPoint joinPoint){
        try {
            long start = System.currentTimeMillis();
            Object o = joinPoint.proceed();
            long time = System.currentTimeMillis() - start;
            Object target = joinPoint.getTarget();
            String className = target.getClass().getName();
            MethodSignature signature = (MethodSignature)joinPoint.getSignature();
            Method method = signature.getMethod();
            String methodName = method.getName();
            ActionLog actionLog = method.getAnnotation(ActionLog.class);
            LogPo logPo = new LogPo();
            logPo.setState(actionLog.value());
            logPo.setType(actionLog.type().getMessage());
            JSONArray array = new JSONArray();
            array.add(joinPoint.getArgs());
            logPo.setParams(array.toString());
            logPo.setClassName(className);
            logPo.setMethodName(methodName);
            logPo.setClassMethodName(String.format("%s.%s", className, methodName));
            logPo.setTime(time);
            logPo.setResult(o);
            logPo.setCreateTime(LocalDateTime.now());
            beanMapper.insert(logPo);
            return o;
        }catch (Throwable e){
            e.printStackTrace();
        }
        return null;
    }
}
